package com.enpronomics.pcall.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.enpronomics.pcall.R;
import com.enpronomics.pcall.ServiceManager;
import com.enpronomics.pcall.receivers.PanicReceiver;

public class MainActivity extends Activity implements OnClickListener {
	/** Called when the activity is first created. */

	private Button advancedBtn, serviceRequestBtn, settingsBtn;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		ServiceManager.setStringSetting(this, ServiceManager.MESSAGE_TYPE,"Panic");
		initialVariables();
		registerPanicReciver();
		
		settingsBtn = (Button) findViewById(R.id.settings_button);
		advancedBtn = (Button) findViewById(R.id.advanced_button);
		serviceRequestBtn = (Button) findViewById(R.id.service_request_button);

		settingsBtn.setOnClickListener(this);
		advancedBtn.setOnClickListener(this);
		serviceRequestBtn.setOnClickListener(this);

	}

	private void registerPanicReciver(){
		try {
			IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
			filter.addAction(Intent.ACTION_SCREEN_OFF);
			PanicReceiver panicReceiver=new PanicReceiver();
			try{unregisterReceiver(panicReceiver);} catch (Exception e) {}
			registerReceiver(panicReceiver, filter);//new PanicReceiver()
		} catch (Exception e) {
			Toast.makeText(this, "Exception:" + e.toString(),Toast.LENGTH_LONG).show();
		}
	}
	private void initialVariables() {
		if (ServiceManager.getStringSetting(this, ServiceManager.KEY_NAME)
				.equals("None")) {
			final EditText input = new EditText(this);
			final CheckBox panic = new CheckBox(this);
			panic.setText("Activation");
			LinearLayout linearLayout = new LinearLayout(this);
			linearLayout.setOrientation(LinearLayout.VERTICAL);
			linearLayout.addView(input);
			linearLayout.addView(panic);
			new AlertDialog.Builder(this)
					.setTitle("pCall")
					.setMessage("Enter Your Name:")
					.setView(linearLayout)
					.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									ServiceManager.setStringSetting(
											MainActivity.this,
											ServiceManager.KEY_NAME, input
													.getText().toString());
									ServiceManager.setBoolSetting(
											MainActivity.this,
											ServiceManager.KEY_PANIC,
											panic.isChecked());
								}
							})
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									dialog.dismiss();
								}
							}).show();
		}
		ServiceManager.setStringSettingIfEmpty(this,
				ServiceManager.KEY_PANIC_SMS_NUMBER, "+447800002197");
		ServiceManager.setStringSettingIfEmpty(this,
				ServiceManager.KEY_PANIC_CALL_NUMBER, "+441757212155");
		ServiceManager.setStringSettingIfEmpty(this,
				ServiceManager.KEY_POSITION_REPORT_NUMBER, "+447800002197");
		ServiceManager.setStringSettingIfEmpty(this,
				ServiceManager.KEY_AUTO_ASSISTANCE_NUMBER, "+441757704459");
		ServiceManager.setIntSettingIfEmpty(this,
				ServiceManager.KEY_SOS_REPETITION, 1);
		ServiceManager.setIntSettingIfEmpty(this,
				ServiceManager.KEY_ACTION_INTERVAL, 5);
	}

	@Override
	public void onClick(View v) {
		/*
		 * DisplayMetrics displaymetrics = new DisplayMetrics();
		 * getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		 * int ht = displaymetrics.heightPixels;
		 * 
		 * LinearLayout ll = (LinearLayout)findViewById(R.id.toplinearLayout);
		 * ll.setPadding(200, 250, 100, 50);
		 * 
		 * int x = ll.getWidth(); int y = ll.getHeight(); DisplayMetrics
		 * displaymetrics = new DisplayMetrics();
		 * getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		 * int ht = displaymetrics.heightPixels; int wt =
		 * displaymetrics.widthPixels;
		 * 
		 * Display display = getWindowManager().getDefaultDisplay(); int width =
		 * display.getWidth(); int height = display.getHeight();
		 * 
		 * //int width = getWindow().getCurrentFocus().getWidth(); //int height
		 * = getWindow().getCurrentFocus().getHeight();
		 * //settingsBtn.setText(""+x+" "+y);
		 * //Log.v("width and height"+width+" "+height, "onReceive()");
		 * Log.v("width and height"+x+" "+y, "onReceive()");
		 */

		if (v == settingsBtn) {
			startActivity(new Intent(MainActivity.this, SettingsActivity.class));
		} else if (v == advancedBtn) {
			startActivity(new Intent(MainActivity.this,
					AdvancedSettingsActivity.class));
		} else if (v == serviceRequestBtn) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Send position report?")
					.setCancelable(false)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									ServiceManager.setStringSetting(
											MainActivity.this,
											ServiceManager.MESSAGE_TYPE,
											"ServiceRequest");
									startActivity(new Intent(MainActivity.this,
											PanicStartActivity.class));
								}
							})
					.setNegativeButton("No",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							}).show();

		}
	}
	
	@Override 
	public boolean onKeyDown(int keyCode, KeyEvent event)  { 
	    if (  Integer.valueOf(android.os.Build.VERSION.SDK) < 7 //Instead use android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR 
	            && keyCode == KeyEvent.KEYCODE_BACK 
	            && event.getRepeatCount() == 0) { 
	        // Take care of calling this method on earlier versions of 
	        // the platform where it doesn't exist. 
	        onBackPressed(); 
	    } 
	 
	    return super.onKeyDown(keyCode, event); 
	} 
	 
	@Override 
	public void onBackPressed() { 

//		KeyEvent.KEYCODE_HOME
	    // This will be called either automatically for you on 2.0 
	    // or later, or by the code above on earlier versions of the 
	    // platform. 
	    return; 
	} 

//
//	@Override
//	public void onActivityResult(int reqCode, int resultCode, Intent data) {
//		super.onActivityResult(reqCode, resultCode, data);
//		try {
//			if (resultCode == Activity.RESULT_OK) {
//				Uri contactData = data.getData();
//				Cursor c = managedQuery(contactData, null, null, null, null);
//				if (c.moveToFirst()) {
//					telNumber = c
//							.getString(c
//									.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
//					telNumber = telNumber.replace("-", "");
//					new MyLocation().init(this, locationResult);
//				}
//			}
//		} catch (Exception ex) {
//		}
//	}
//
//	public LocationResult locationResult = new LocationResult() {
//		@Override
//		public void gotLocation(final Location location) {
//			String locationStr;
//			if (location == null)
//				locationStr = "No location Found";
//			else
//				locationStr = ServiceManager.getLocationStr(location);
//
//			if (isFindLocation) {
//				ServiceManager.sendSMS(MainActivity.this, telNumber,
//						messageText);
//				isFindLocation = false;
//			} else
//				ServiceManager.sendSMS(MainActivity.this, telNumber,
//						messageText + "\n" + locationStr);
//		}
//	};
}
